﻿using Furion.DatabaseAccessor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FurionApiDemo.Core.DatabaseAccessor
{
    public static class FakeDeleteExtensions
    {
        /// <summary>
        /// 假删除
        /// </summary>
        /// <param name="repository">扩展 仓储</param>
        /// <param name="id">主键Id</param>
        public static async Task FakeDeleteAsync<TEntity>(
            this IPrivateRepository<TEntity> repository, int id)
            where TEntity : class, IPrivateEntity, new()
        {
            // 根据泛型 创建一个新model
            var entity = Activator.CreateInstance<TEntity>();

            // 读取主键
            var keyProperty = repository.EntityType.FindPrimaryKey().Properties.AsEnumerable().FirstOrDefault()
                ?.PropertyInfo;
            if (keyProperty == null)
                throw new InvalidOperationException("没有找到key");

            // 设置主键ID的值
            keyProperty.SetValue(entity, id);

            // 查找 假删除 特性
            var fakeDeleteProperty = repository.EntityType.ClrType
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .FirstOrDefault(u => u.IsDefined(typeof(FakeDeleteAttribute), true));
            if (fakeDeleteProperty == null)
                throw new InvalidOperationException("实体中没有找到FakeDelete特性");

            // 读取假删除的名称和属性
            var fakeDeleteAttribute = fakeDeleteProperty.GetCustomAttribute<FakeDeleteAttribute>(true);
            if (fakeDeleteAttribute == null)
                throw new InvalidOperationException("未读取到FakeDeleteAttribute特性");

            // 设置 假删除IsDeleted  状态为true
            fakeDeleteProperty.SetValue(entity, fakeDeleteAttribute.State);

            // 数据库更新
            await repository.UpdateIncludeAsync(entity, new[] { fakeDeleteProperty.Name });
        }
    }
}
